// 搜索框
let searchContents = document.querySelectorAll('.header-m input');
for(let i = 0; i < searchContents.length; i++) {
	let searchContent = searchContents[i];
	searchContent.placeholder = '最新上架';
	let searchButton = searchContent.nextElementSibling;
	searchButton.onclick = function() {
		let searchValue = searchContent.value.trim();
		if(searchValue) {
			location.href = '/page/user/search/list.html?keyword=' + searchValue;
		} else if(searchContent.placeholder != '搜索商品') {
			location.href = '/page/user/search/list.html?keyword=' + searchContent.placeholder;
		}
	}
	searchContent.onkeydown = function(e) {
		e = e || window.event;
		if(e.keyCode == 13 || e.keyCode == 108) {
			// 回车键
			searchButton.click();
		}
	}
}
let args = location.search;
if(!args) {
	// 若没有传值则跳转到首页
	location.replace('');
}
/* 格式化日期 */
Date.prototype.format = function(fmt) { 
	let o = {
		"M+" : this.getMonth()+1, // 月份
　　　		"d+" : this.getDate(), // 日
　　　　	"h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, // 小时
　　　　	"H+" : this.getHours(), // 小时
　　　　	"m+" : this.getMinutes(), // 分
　　　　	"s+" : this.getSeconds(), // 秒
　　　　	"q+" : Math.floor((this.getMonth()+3)/3), // 季度
　　　　	"S" : this.getMilliseconds() // 毫秒
　　	};
　　	if(/(y+)/.test(fmt)) {
　　　　	fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(let k in o) {
　　　		if(new RegExp("("+ k +")").test(fmt))
　　　　		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
	}
	return fmt;
}

// 图片
let box = document.getElementById('imgBox');
let smallBox = box.children[0];
let bigBox = box.children[1];
let smallImage = smallBox.children[0];
let imgMask = smallBox.children[1];
let bigImage = bigBox.children[0];
let goodsInfo = document.querySelector('.goods-info');
args = args.substring(1);
ajax({
	type: 'POST',
	async: false,
	url: `/goods/${args}/desc`,
	success: function(xhr) {
		let arg = JSON.parse(xhr.responseText);
		if(arg.code == 3110) {
			// 未找到商品则跳转到首页
			location.replace('');
		} else if(arg.code == 200) {
			let data = arg.data;
			// 设置图片
			let _imgPath = data.imgPath;
			let imgPathIndex = _imgPath.indexOf(';')
			if(imgPathIndex != -1) {
				_imgPath = _imgPath.substring(0, imgPathIndex);
				// 有多张图片
				let otherImg = box.children[2];
				let imgs = data.imgPath.split(';');
				for(let i = 0; i < imgs.length; i++) {
					let img = document.createElement('img');
					img.src = imgs[i];
					if(i == 0) {
						img.className = 'on';
					}
					otherImg.appendChild(img);
					img.onmousemove = function() {
						removeStyle(otherImg, 'on');
						this.className = 'on';
						smallImage.src = this.src;
						bigImage.src = this.src;
					}
				}
			}
			smallImage.src = _imgPath;
			bigImage.src = _imgPath;
			// 设置商品详情
			goodsInfo.querySelector('.info-desc p').innerText = data.details;
			// 设置商品名称
			goodsInfo.querySelector('.info-name em').innerText = data.name;
			// 设置商品名称
			goodsInfo.querySelector('.info-price strong').innerText = data.realPrice;
			// 设置商品标签
			let goodsLabel = goodsInfo.children[3];
			let labels = data.label.split('####TPL####');
			labels.forEach(label => {
				let labelDiv = document.createElement('div');
				labelDiv.innerText = label;
				goodsLabel.appendChild(labelDiv);
			});
			// 设置发布日期
			goodsInfo.querySelector('.info-date em').innerText = new Date(data.time).format('yyyy-MM-dd HH:mm');
			// 设置剩余数量
			goodsInfo.querySelector('.info-count-free em').innerText = data.count - data.reservedCount;
			// 设置已预约数量
			goodsInfo.querySelector('.info-count-order em').innerText = data.reservedCount;
			// 设置商品卖家
			goodsInfo.querySelector('.info-count-contact em').innerText = data.user.department + " " + data.user.classname + " " + data.user.nickname
		}
	}
});
/* 页面移动头部移动 */
let headerMove = document.getElementById('headerMove'); // 头部移动栏
/*
	功能：解决获取页面滚动距离兼容性问题
*/
function getScrollTop() {
	return document.body.scrollTop || document.documentElement.scrollTop;
}
document.onscroll = function() {
	let scrollTop = getScrollTop();
	if(scrollTop >= 195) {
		headerMove.style.display = 'block';
	} else {
		headerMove.style.display = 'none';
	}
}
/* 设置鼠标移入elevator事件 */
let elevator = document.getElementById('elevator');
let cartItem = elevator.querySelectorAll('.elevator-inner')[0];
let feedbackItem = elevator.querySelectorAll('.elevator-inner')[1];
let toTopItem = elevator.querySelectorAll('.elevator-inner')[2];
cartItem.parentNode.onmouseover = function() {
	cartItem.previousElementSibling.style.backgroundColor = ' #549ec5';
	setTimeout(() => {
		cartItem.style.left = '-60px';
	}, 200);
}
cartItem.parentNode.onmouseleave = function() {
	setTimeout(() => {
		cartItem.style.left = '0';
	}, 200);
	setTimeout(() => {
		cartItem.previousElementSibling.style.backgroundColor = ' #7a6e6e';
	}, 400);
	
}
feedbackItem.parentNode.onmouseover = function() {
	feedbackItem.previousElementSibling.style.backgroundColor = ' #549ec5';
	setTimeout(() => {
		feedbackItem.style.left = '-60px';
	}, 100);
}
feedbackItem.parentNode.onmouseleave = function() {
	setTimeout(() => {
		feedbackItem.style.left = '0';
	}, 100);
	setTimeout(() => {
		feedbackItem.previousElementSibling.style.backgroundColor = ' #7a6e6e';
	}, 400);
}
toTopItem.parentNode.onmouseover = function() {
	toTopItem.previousElementSibling.style.backgroundColor = ' #549ec5';
	setTimeout(() => {
		toTopItem.style.left = '-60px';
	}, 100);
}
toTopItem.parentNode.onmouseleave = function() {
	setTimeout(() => {
		toTopItem.style.left = '0';
	}, 100);
	setTimeout(() => {
		toTopItem.previousElementSibling.style.backgroundColor = ' #7a6e6e';
	}, 400);
}
/* 图片放大镜效果 */
// 获取鼠标在页面上的位置
function getPage(e) {
	var pageX = e.pageX || e.clientX + getScroll().scrollLeft;
	var pageY = e.pageY || e.clientY + getScroll().scrollTop;
	return {
		pageX: pageX,
		pageY: pageY
	}
}
smallBox.onmouseover = function() {
	imgMask.style.display = 'block';
    bigBox.style.display = 'block';
}

smallBox.onmouseout = function() {
	imgMask.style.display = 'none';
    bigBox.style.display = 'none';
}

smallBox.onmousemove = function(e) {
    e = e || window.even;
    let x = getPage(e).pageX - box.offsetLeft; // offsetLeft是子元素和父元素之间的距离，所以不能用smallBox
    let y = getPage(e).pageY - box.offsetTop;
    let maskX = x - imgMask.offsetWidth / 2;
    let maskY = y - imgMask.offsetHeight / 2;
    maskX = maskX < 0 ? 0 : maskX;
    maskY = maskY < 0 ? 0 : maskY;
    maskX = maskX > (smallBox.offsetWidth - imgMask.offsetWidth) ? (smallBox.offsetWidth - imgMask.offsetWidth) : maskX;
    maskY = maskY > (smallBox.offsetWidth - imgMask.offsetWidth) ? (smallBox.offsetWidth - imgMask.offsetWidth) : maskY;
    imgMask.style.left = maskX + 'px';
    imgMask.style.top = maskY + 'px';
    // imgMask移动的距离 / imgMask最大能够移动的距离  = 大图片移动的距离 / 大图片最大能够移动的距离
    let maskMax = smallBox.offsetWidth - imgMask.offsetWidth;
    let bigImageMax = bigImage.offsetWidth - bigBox.offsetWidth;
    let bigImageX = maskX / maskMax * bigImageMax;
    let bigImageY = maskY / maskMax * bigImageMax;
    bigImage.style.left = -bigImageX + 'px';
    bigImage.style.top = -bigImageY + 'px';
}
/* 对商品数量加进行减操作 */
let chooseCount = document.getElementById('chooseCount');
let countFree = document.getElementById('countFree');
let plusButton = chooseCount.querySelectorAll('button')[0];
let reduceButton = chooseCount.querySelectorAll('button')[1];
/*
	功能：设置加减按钮的样式 
*/
function setButtonStyle(button) {
	let freeCount = Number(countFree.querySelector('em').innerText);
	let count = Number(chooseCount.querySelector('input').value);
	if(freeCount <= 1) {
		button.style.cursor = 'default';
		button.style.color = '#ccc';
		return;
	}
	if(count >= freeCount || count <= 1) {
		if((count == 1 && button.innerText == '+') || (count == freeCount && button.innerText == '-')) {
			button.style.cursor = 'pointer';
			button.style.color = '#666';
		} else {
			button.style.cursor = 'default';
			button.style.color = '#ccc';
		}	
	} else {
		button.style.cursor = 'pointer';
		button.style.color = '#666';
	}
}
setButtonStyle(plusButton);
plusButton.onclick = function() {
	if(this.style.cursor == 'pointer') {
		let count = Number(chooseCount.querySelector('input').value);
		chooseCount.querySelector('input').value = count + 1;
		setButtonStyle(this);
		setButtonStyle(reduceButton);
	}
}
reduceButton.onclick = function() {
	if(this.style.cursor == 'pointer') {
		let count = Number(chooseCount.querySelector('input').value);
		chooseCount.querySelector('input').value = count - 1;
		setButtonStyle(this);
		setButtonStyle(plusButton);
	}
}
// 添加购物车，去预约
let toCart = chooseCount.nextElementSibling;
let cart = toCart.children[0];
let order = toCart.children[1];
cart.onclick = function() {
	let countValue = chooseCount.querySelector('input').value;
	if(!/^\d+$/.test(countValue)) {
		toast('购买数量有误');
		return;
	}
	let count = Number(countValue);
	if(count > Number(goodsInfo.querySelector('.info-count-free em').innerText)) {
		toast('购买数量不能大于剩余数量');
	} else {
		// 确定
		ajax({
			type: 'POST',
			async: true,
			url: '/cart/add',
			data: {
				id: args,		
				count: count
			},
			success: function(xhr) {
				let arg = JSON.parse(xhr.responseText);
				if(arg.code == 200) {
					toast('成功加入购物车', '#84cc77');
				} else if(arg.code == 3200) {
					toast('购买数量不能大于剩余数量');
				} else if(arg.code == 3201) {
					toast('购买数量有误');
				} else if(arg.code == 3110) {
					location.reload(true);
				} else if(arg.code == 3020) {
					location.replace('/page/user/login.html');
				} else if(arg.code == 3202) {
					mask.style.display = 'block';
					mask.innerHTML = `<div class="mask-wrap" style="position: absolute; top: 50%; left: 50%; margin-top: -59px;margin-left: -195px;width: 390px;background-color: #fff;border-radius: 4px;border: 1px solid #ddd;box-shadow: 0 0 7px #eee;">
						<div class="mask-h clearfix">
							<span style="float: left;width: 34px;height: 34px;background: url(/images/tip_icon.png) no-repeat;margin-top: 10px;margin-left: 10px;"></span>
							<span style="float: left;height: 53px;line-height: 53px;padding-left: 10px;font-size: 14px;">提示</span>
							<span style="float: right;width: 24px;height: 24px;background: url(/images/x_icon.png) no-repeat;cursor: pointer;margin-top: 9px;margin-right: 8px;" title="关闭面板" ></span>
						</div>
						<div class="mask-content" style="padding: 5px 22px;padding-bottom: 40px;font-size: 14px;">${arg.message}</div>
			  		</div>`;
					let maskH = mask.querySelector('.mask-h');
					maskH.children[2].onclick = function() {
						// 顶部关闭icon
						removeAllChildren(mask);
						mask.style.display = 'none';
					}
					setTimeout(() => {
						removeAllChildren(mask);
						mask.style.display = 'none';
					}, 4000);
				}
			}
		});
	}
}
order.onclick = function() {
	let countValue = chooseCount.querySelector('input').value;
	if(!/^\d+$/.test(countValue)) {
		toast('购买数量有误');
		return;
	}
	let count = Number(countValue);
	if(count > Number(goodsInfo.querySelector('.info-count-free em').innerText)) {
		toast('购买数量不能大于剩余数量');
	} else {
		// 确定
		ajax({
			type: 'POST',
			async: true,
			url: '/order/add',
			data: {
				id: args,		
				count: count
			},
			beforeSend: function() {
				// 显示等待图片
				mask.style.display = 'block';
				mask.style.backgroundColor = 'rgba(0, 0, 0, 0)';
				mask.innerHTML = `<div class="mask-wrap" style="position: absolute; top: 50%; left: 50%; margin-top: -45px;margin-left: -45px;width: 90px;height: 90px;background: url(/images/loading2.gif) no-repeat;background-size: 90px;">
								  </div>`;
			},
			success: function(xhr) {
				removeAllChildren(mask);
				mask.style.display = 'none';
				let arg = JSON.parse(xhr.responseText);
				if(arg.code == 200) {
					location.href = '/page/user/buy/order.html?' + arg.data;
				} else if(arg.code == 3020) {
					location.replace('/page/user/login.html');
				} else if(arg.code == 3300) {
					toast(arg.message);
				} else if(arg.code == 3101) {
					toast('请先完善您的个人信息');
				} else {
					toast('系统繁忙，请刷新页面后重试');
					setTimeout(() => {
						location.reload(true);
					}, 3000);
				} 
			}
		});
	}
}
/* 留言板选择排序 */
let commentChoose = document.getElementById('commentChoose');
let commentPublish = commentChoose.nextElementSibling;
let commentArea = commentPublish.nextElementSibling;
let hotSort = commentChoose.children[0];
let newSort = commentChoose.children[1];
let data = null;
// 请求用户登录状态
let userBar1 = document.getElementById('userBar1');
let userBar2 = document.getElementById('userBar2');
// 获取sno和pwd，发送至服务器校验
let value = getCookieValue('userCookie');
// 若没有值则为未登录状态
if(!value) {
	userBar1.innerHTML = `<a href="/page/user/login.html">你好，请登录</a>`;
	userBar2.innerHTML = `<a class="ht" href="/page/user/regist.html">立即注册</a>`;
	commentPublish.innerHTML = `<div class="publish-l">
					<img src="/images/face/default.jpg" alt="用户头像" />
				</div>
				<div class="publish-m">
					<div class="publish-login-wrap">请先<a class="publish-tologin" href="/page/user/login.html" target="_blank">登录</a>后发表留言 (・ω・)</div>
				</div>
				<button class="publish-submit" style="background-color: #e5e9ef;cursor: default;color: #b8c0cc;">发表留言</button>`;
} else {
	// 若有值，传至服务器校验该值的合法性
	let snoValue = value.split('#_TPLAssociation_#')[0];
	let pwdValue = value.split('#_TPLAssociation_#')[1];
	ajax({
		type: 'POST',
		url: '/user/isLogin',
		async: true,
		data: {
			sno: snoValue,
			pwd: pwdValue
		},
		success: function(xhr) {
			let arg = JSON.parse(xhr.responseText);
			data = arg.data;
			if(arg.code == 200 && arg.message == 'success') {
				// 登录成功
				userBar1.innerHTML = `<a class="ht" href="/page/user/space">${data.nickname}</a>`
				userBar2.innerHTML = `<a href="/user/logout?redirectURL=${location.href}">退出</a>`
				commentPublish.innerHTML = `<div class="publish-l">
						<img src="${data.imgPath}" alt="用户头像" />
					</div>
					<div class="publish-m">
						<textarea cols="80" name="msg" rows="5" placeholder="发一条友善的留言吧" maxlength="500"></textarea>
					</div>
					<button class="publish-submit">发表留言</button> `;	
				
				/* 发布留言文本域效果 */
				let textarea = document.getElementsByTagName('textarea');
				textarea[0].onfocus = focusEvent;
				textarea[0].onblur = blurEvent;
				/* 发布留言 */
				let publishSubmit = commentPublish.querySelector('button');
				publishSubmit.onclick = function() {
					let textarea = this.previousElementSibling.children[0];
					let contentStr = textarea.value.trim()
					if(contentStr.length > 0 && publishSubmit.innerText != '发送中') {
						ajax({
							type: 'POST',
							url: '/comment/add',
							async: true,
							data: {
								id: args,
								content: encodeURIComponent(contentStr)
							},
							beforeSend: function() {
								publishSubmit.style = 'background-color: #e5e9ef;cursor: default;color: #b8c0cc;padding: 0;';
								publishSubmit.innerText = '发送中';
								textarea.disabled = 'disabled';
							},
							success: function(xhr) {
								// 还原之前的效果
								publishSubmit.style = '';
								publishSubmit.innerText = '发表留言';
								textarea.disabled = '';
								// 清空留言板的内容
								textarea.value = '';
								let arg2 = JSON.parse(xhr.responseText);
								if(arg2.code == 3110) {
									toast('系统繁忙，请刷新页面后重试');
									setTimeout(() => {
										location.reload(true);
									}, 3000);
								} else if(arg2.code == 3020) {
									location.replace('/page/user/login.html');
								} else if(arg2.code == 300) {
									toast('请输入留言内容');
								} else if(arg2.code == 200) {
									// 发布成功效果
									let div = document.createElement('div');
									div.className = 'publish-suc';
									div.innerText = '发布成功';
									commentPublish.appendChild(div);
									setTimeout(() => {
										div.remove();
									}, 2000);
									// 添加留言
									let li = document.createElement('li');
									li.className = 'clearfix';
									let _time = new Date(arg2.data.time).format('yyyy-MM-dd HH:mm');
									li.innerHTML = `<div class="content-img">
														<img src="${data.imgPath}" alt="用户头像" />
													</div>
													<div class="content-main">
														<span class="content-name">${data.nickname}</span>
														<p>${contentStr}</p>
														<div class="content-b clearfix">
															<span class="content-time fl">${_time}</span>
															<span class="content-like fl">0</span>
															<span class="content-reply fl">回复</span>
														</div>
														<div class="comment-reply" style="display: block">
															<ul></ul>
														</div>
														<div class="comment-publish clearfix" style="display: none;">
															<div class="publish-l">
																<img src="${data.imgPath}" alt="用户头像" />
															</div>
															<div class="publish-m">
																<textarea cols="80" name="msg" rows="5" placeholder="回复 @${data.nickname}：" maxlength="500"></textarea>
															</div>
															<button class="publish-submit">发表留言</button>
														</div>
													</div>`;
									// 在最前面加入
									if(commentArea.children[0].children.length == 0) {
										commentArea.children[0].appendChild(li);
									} else {
										commentArea.children[0].insertBefore(li,commentArea.children[0].children[0]);
									}
									// 给点赞和回复注册事件
									li.querySelector('.content-like').onclick = function() {
										likeButtonEvent.call(this,arg2.data.commentId);
									}
									li.querySelector('.content-reply').onclick = function() {
										replyButtonEvent.call(this,arg2.data.commentId);
									};
									// 留言数加1
									addCommentCount();
								}
							}
						});
					}
				}	
			} else {
				// 未登录
				userBar1.innerHTML = `<a href="/page/user/login.html">你好，请登录</a>`;
				userBar2.innerHTML = `<a class="ht" href="/page/user/regist.html">立即注册</a>`;
				commentPublish.innerHTML = `
					<div class="publish-l">
						<img src="/images/face/default.jpg" alt="用户头像" />
					</div>
					<div class="publish-m">
						<div class="publish-login-wrap">请先<a class="publish-tologin" href="/page/user/login.html" target="_blank">登录</a>后发表留言 (・ω・)</div>
					</div>
					<button class="publish-submit" style="background-color: #e5e9ef;cursor: default;color: #b8c0cc;">发表留言</button>`;
			}
		}
	});
}

/*
	功能：留言板获取焦点事件
*/
function focusEvent() {
	this.style.backgroundColor = '#fff';
	this.style.borderColor = '#549ec5';
}
/*
	功能：留言板失去焦点事件
*/
function blurEvent() {
	this.style.backgroundColor = '#f4f5f7';
	this.style.borderColor = '#e5e9ef';
}
/* 留言区域效果 */
let commentLikes = commentArea.querySelectorAll('.content-like');
let replyButtons = commentArea.querySelectorAll('.content-reply');

/*
	功能：点击点赞按钮事件
	参数1：商品留言id
*/
function likeButtonEvent(id) {
	let _this = this;
	if(this.style.background.indexOf('click') == -1) {
		ajax({
			type: 'POST',
			url: '/comment/like',
			async: true,
			data: {
				id1: id,
				id2: args
			},
			success: function(xhr) {
				let arg = JSON.parse(xhr.responseText);
				if(arg.code == 200) {
					_this.style.background = 'url(/images/like_click_icon.png) no-repeat';
					let count = Number(_this.innerText);
					_this.innerText = count + 1;
				} else if(arg.code == 3020) {
					toast('请先登录');
				} else if(arg.code == 3400) {
					toast('系统繁忙，请刷新页面后重试');
					setTimeout(() => {
						location.reload(true);
					}, 3000);
				}
			}
		});
		
	}
}
/*
	功能：使总留言数加1
*/
function addCommentCount() {
	let commentCount = Number(commentChoose.previousElementSibling.children[0].innerText);
	commentChoose.previousElementSibling.children[0].innerText = commentCount + 1;
}
/*
	功能：使总留言数减1
*/
function reduceCommentCount() {
	let commentCount = Number(commentChoose.previousElementSibling.children[0].innerText);
	if(commentCount >= 1) {
		commentChoose.previousElementSibling.children[0].innerText = commentCount - 1;
	}
}

/*
	功能：点击回复按钮事件
	参数1：商品留言id
*/
function replyButtonEvent(id) {
	let publish = this.parentNode.nextElementSibling.nextElementSibling;
	let button = publish.children[2];
	if(publish.style.display.indexOf('none') != -1) {
		publish.style.display = 'block';
		if(!data) {
			// 未登录
			let publishM = publish.children[1];
			removeAllChildren(publishM);
			let div = document.createElement('div');
			div.className = 'publish-login-wrap';
			div.innerHTML = `请先<a class="publish-tologin" href="/page/user/login.html" target="_blank">登录</a>后发表留言 (・ω・)`;
			publishM.appendChild(div);
			button.style = 'background-color: #e5e9ef;cursor: default;color: #b8c0cc;';
			return;
		} else {
			// 设置用户头像
			console.log(publish.parentNode.previousElementSibling.children[0]);
			publish.querySelector('img').src = data.imgPath;
		}
		let textarea = publish.querySelector('textarea');
		textarea.onfocus = focusEvent;
		textarea.onblur = blurEvent; 
		textarea.focus();
		let _this = this;
		button.onclick = function() {
			let contentStr = textarea.value.trim();
			if(contentStr.length > 0 && button.innerText != '发送中') {
				ajax({
					type: 'POST',
					url: '/reply/addByComment',
					async: true,
					data: {
						id1: id,
						id2: args,
						content: encodeURIComponent(contentStr)
					},
					beforeSend: function() {
						button.style = 'background-color: #e5e9ef;cursor: default;color: #b8c0cc;padding: 0;';
						button.innerText = '发送中';
						textarea.disabled = 'disabled';
					},
					success: function(xhr) {
						// 还原之前的效果
						button.style = '';
						button.innerText = '发表留言';
						textarea.disabled = '';
						// 清空留言板的内容
						textarea.value = '';
						let arg = JSON.parse(xhr.responseText);
						if(arg.code == 3400) {
							toast('系统繁忙，请刷新页面后重试');
							setTimeout(() => {
								location.reload(true);
							}, 3000);
						} else if(arg.code == 3020) {
							location.replace('/page/user/login.html');
						} else if(arg.code == 300) {
							toast('请输入回复内容');
						} else if(arg.code == 200) {
							// 发布成功效果
							let div = document.createElement('div');
							div.className = 'publish-suc';
							div.innerText = '发布成功';
							publish.appendChild(div);
							setTimeout(() => {
								div.remove();
							}, 2000);
							// 添加回复
							let commentReply = _this.parentNode.nextElementSibling;
							let commentReplyUl = commentReply.children[0];
							if(commentReply.style.display == 'none') {
								commentReply.style.display = 'block';
							}
							let li = document.createElement('li');
							li.className = 'clearfix';
							let _time = new Date(arg.data.time).format('yyyy-MM-dd HH:mm');
							li.innerHTML = `<div class="content-img">
												<img src="${data.imgPath}" alt="用户头像" />
											</div>
											<div class="content-main">
												<span class="content-name">${data.nickname}</span>
												<p>${contentStr}</p>
												<div class="content-b">
													<span class="content-time">${_time}</span>
													<span class="content-delete">删除</span>
												</div>
											</div>`;
							commentReplyUl.appendChild(li);
							// 回复留言板隐藏
							publish.style.display = 'none';
							// 留言数加1
							addCommentCount();
							// 设置点击删除事件
							li.querySelector('.content-delete').onclick = function() {
								// 这里未做删除提示
								ajax({
									type: 'POST',
									url: '/reply/deleteByComment',
									async: true,
									data: {
										id1: arg.data.rid,
										id2: id
									},
									success: function(xhr) {
										let arg2 = JSON.parse(xhr.responseText);
										if(arg2.code == 3400) {
											toast('系统繁忙，请刷新页面后重试');
											setTimeout(() => {
												location.reload(true);
											}, 3000);
										} else if(arg2.code == 3020) {
											location.replace('/page/user/login.html');
										} else if(arg2.code == 200) {
											removeWorld(li);
											reduceCommentCount();
											toast('删除成功', '#84cc77');
										}
									}
								});
							}
						}
					}
				});
			}	
		}
	} else {
		publish.style.display = 'none';
		button.onclick = null;
	}
}



//请求留言
let loadingDiv = document.createElement('div');
ajax({
	type: 'POST',
	url: '/comment/getComments',
	async: true,
	data: {
		id: args
	},
	beforeSend: function() {
		loadingDiv.style = 'width: 660px;height: 99px;background: url(/images/comment_loading.PNG) no-repeat;margin-top: 60px;';
		commentArea.appendChild(loadingDiv);
	},
	success: function(xhr) {
		loadingDiv.remove();
		let arg3 = JSON.parse(xhr.responseText);
		if(arg3.code == 3400) {
			toast('系统繁忙，请刷新页面后重试');
			setTimeout(() => {
				location.reload(true);
			}, 3000);
		} else if(arg3.code == 200) {
			let comments = arg3.data;
			// 总留言数=留言数+回复数
			let commentCount = comments.length;
			setComments(comments, commentCount);
			// 设置总留言数
			commentChoose.previousElementSibling.children[0].innerText = commentCount;
			// 按时间排序
			newSort.onclick = function() {
				let className = this.className;
				let index;
				if((index = className.indexOf(' on')) == -1) {
					let chooseBar = newSort.nextElementSibling;
					hotSort.className = hotSort.className.substring(0, 10);
					this.className = this.className + ' on';
					chooseBar.style.left = '103px';
					removeAllChildren(commentArea.children[0]);
					comments = comments.sort((a, b) =>  b.time - a.time);
					setComments(comments);
				}
			}
			hotSort.onclick = function() {
				let className = this.className;
				let index;
				if((index = className.indexOf(' on')) == -1) {
					let chooseBar = newSort.nextElementSibling;
					newSort.className = newSort.className.substring(0, 10);
					this.className = this.className + ' on';
					chooseBar.style.left = '0';
					removeAllChildren(commentArea.children[0]);
					comments = comments.sort((a, b) =>  {
						if(b.likeCount == a.likeCount) {
							return b.time - a.time;
						}
						return b.likeCount - a.likeCount;
					});
					setComments(comments);
				}
			}
		}
		
	}
	
});

/*
 * 	添加留言
 * 	参数1：留言集合
 * 	参数2：总留言数
 * 
 * */
function setComments(comments, commentCount) {
	comments.forEach(comment => {
		// 添加留言
		let li = document.createElement('li');
		li.className = 'clearfix';
		let _time = new Date(comment.time).format('yyyy-MM-dd HH:mm');
		let _imgPath = '/images/face/default.jpg';
		li.innerHTML = `<div class="content-img">
							<img src="${comment.user.imgPath}" alt="用户头像" />
						</div>
						<div class="content-main">
							<span class="content-name">${comment.user.nickname}</span>
							<p>${comment.content}</p>
							<div class="content-b clearfix">
								<span class="content-time fl">${_time}</span>
								<span class="content-like fl">${comment.likeCount}</span>
								<span class="content-reply fl">回复</span>
							</div>
							<div class="comment-reply" style="display: block">
								<ul></ul>
							</div>
							<div class="comment-publish clearfix" style="display: none;">
								<div class="publish-l">
									<img src="${_imgPath}" alt="用户头像" />
								</div>
								<div class="publish-m">
									<textarea cols="80" name="msg" rows="5" placeholder="回复 @${comment.user.nickname}：" maxlength="500"></textarea>
								</div>
								<button class="publish-submit">发表留言</button>
							</div>
						</div>`;
		// 添加回复信息
		let replys = comment.replyList;
		if(replys) {
			if(commentCount) {
				commentCount = commentCount + replys.length;
			}
			let replyUl = li.querySelector('.comment-reply ul');
			replys.forEach(reply => {
				let replyLi = document.createElement('li');
				replyLi.className = 'clearfix';
				let _time = new Date(reply.time).format('yyyy-MM-dd HH:mm');
				replyLi.innerHTML = `<div class="content-img">
									<img src="${reply.user.imgPath}" alt="用户头像" />
								</div>
								<div class="content-main">
									<span class="content-name">${reply.user.nickname}</span>
									<p>${reply.content}</p>
									<div class="content-b">
										<span class="content-time">${_time}</span>
									</div>
								</div>`;
				if(data && reply.user.uid == data.uid) {
					let deleteSpan = document.createElement('span');
					deleteSpan.className = 'content-delete';
					deleteSpan.innerText = '删除';
					replyLi.querySelector('.content-b').appendChild(deleteSpan);
					// 点击删除事件
					deleteSpan.onclick = function() {
						// 这里未做删除提示
						ajax({
							type: 'POST',
							url: '/reply/deleteByComment',
							async: true,
							data: {
								id1: reply.rid,
								id2: comment.commentId
							},
							success: function(xhr) {
								let arg2 = JSON.parse(xhr.responseText);
								if(arg2.code == 3400) {
									toast('系统繁忙，请刷新页面后重试');
									setTimeout(() => {
										location.reload(true);
									}, 3000);
								} else if(arg2.code == 3020) {
									location.replace('/page/user/login.html');
								} else if(arg2.code == 200) {
									removeWorld(li);
									reduceCommentCount();
									toast('删除成功', '#84cc77');
								}
							}
						});
					}
				}
				replyUl.appendChild(replyLi);
			});
		}
		commentArea.children[0].appendChild(li);
		// 给点赞和回复注册事件
		li.querySelector('.content-like').onclick = function() {
			likeButtonEvent.call(this,comment.commentId);
		}
		li.querySelector('.content-reply').onclick = function() {
			replyButtonEvent.call(this,comment.commentId);
		};
	});
}